package cn.wangkai.peanut.util.mvc;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import cn.wangkai.peanut.lang.ActionException;
import cn.wangkai.peanut.lang.LoginFailException;
import cn.wangkai.peanut.util.RequestContext;
import cn.wangkai.peanut.util.StackTraceUtils;
import cn.wangkai.peanut.util.mvc.exception.PageNotFoundException;

public class ExceptionUtil {
	public static ActionForward getActionForward(Throwable e,RequestContext context){
		ActionForward fr = null;
		Map<String, Object> root = new HashMap<String, Object>();
//		IllegalAccessException){
//			e = ((IllegalAccessException)e).getCause();
//		}else if (e instanceof IllegalArgumentException){
//			e = ((IllegalArgumentException)e).getCause();
//		}else if (e instanceof
		if(e instanceof InvocationTargetException){
			e = ((InvocationTargetException)e).getTargetException();
			
		}
		if(e instanceof LoginFailException){
			fr = new ActionForward(context.request().getContextPath()+"/passport/login.html");
		}else if(e instanceof PageNotFoundException){
			context.response().setStatus(HttpServletResponse.SC_NOT_FOUND);
			root.put("errmessage", StackTraceUtils.getStackTrace(e));
			fr = new ActionForward("errpage/400",ActionForward.TYPE_VM, root);
		}else if(e instanceof ActionException){
			root.put("errmessage", StackTraceUtils.getStackTrace(e));
			fr = new ActionForward("errpage/100",ActionForward.TYPE_VM, root);
		}else{
			root.put("errmessage", StackTraceUtils.getStackTrace(e));
			context.response().setStatus(HttpServletResponse.SC_BAD_REQUEST);
			fr = new ActionForward("errpage/500",ActionForward.TYPE_VM, root);
		}
		return fr;
	}
}
